package org.cainiaojin.config.primary;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
/**
 * 主数据源配置
 */
@Configuration
@MapperScan(basePackages = "org.cainiaojin.mapper.primary",sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDBConfig {

    private final PrimaryProperties primaryProperties;

    public PrimaryDBConfig(PrimaryProperties primaryProperties){
        this.primaryProperties = primaryProperties;
    }
    @Primary
    @Bean(name="primaryDataSource")
    public DataSource primaryDataSource()  {
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource(); // 修正变量名
        mysqlXADataSource.setURL(primaryProperties.getUrl());
        mysqlXADataSource.setUser(primaryProperties.getUsername());
        mysqlXADataSource.setPassword(primaryProperties.getPassword());
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
        atomikosDataSourceBean.setUniqueResourceName("primaryDataSource");
        return atomikosDataSourceBean;
    }
    @Bean(name="primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml"));
        return bean.getObject();
    }

    @Bean(name="primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
